from qiniu import Auth
from qiniu import put_file, put_data
from qiniu import BucketManager
import qiniu.config


class QiNiu(object):
    """上传七牛云"""
    def __init__(self):
        # 需要填写你的 Access Key 和 Secret Key
        self.access_key = 'qW6e8YZ_rAMD85IsWmRHGStaDJYYpI--VclRG93Y'
        self.secret_key = 'Oj5wtk5MTRg8qXM6Rjk7ssVOTrwMoyWitHYil219'

        # 构建鉴权对象
        self.q = Auth(self.access_key, self.secret_key)

        # 要上传的空间
        self.bucket_name = 'ihomeno1'

    def upload_file(self, key_str):
        """上传文件"""

        # 上传后保存的文件名
        key = key_str

        # 生成上传 Token，可以指定过期时间等
        token = self.q.upload_token(self.bucket_name, key, 3600)

        # 要上传文件的本地路径
        localfile = './02.jpg'
        ret, info = put_file(token, key, localfile)
        # assert ret['key'] == key
        # assert ret['hash'] == etag(localfile)

        # type(info) = <class 'qiniu.http.ResponseInfo'>
        # imfo = _ResponseInfo__response:<Response [200]>, exception:None, status_code:200, text_body:{"hash":"Fv9pEjc86H3jDuTtLq7kuAnKAag0","key":"Fv9pEjc86H3jDuTtLq7kuAnKAag0"}, req_id:dckAAADX_le75XoW, x_log:X-Log
        # type(ret) = <class 'dict'>
        # ret = {'hash': 'Fv9pEjc86H3jDuTtLq7kuAnKAag0', 'key': 'Fv9pEjc86H3jDuTtLq7kuAnKAag0'}

        if info.status_code == 200:
            file_url = ret['key']
            return file_url
        else:
            return ""

    def upload_data(self, key_str, avatar_byte):
        """上传二进制流"""

        # 上传后保存的文件名
        key = key_str

        # 生成上传 Token，可以指定过期时间等
        token = self.q.upload_token(self.bucket_name, key, 3600)

        # 要上传文件的图片二进制流
        image_data = avatar_byte
        ret, info = put_data(token, key, image_data)

        if info.status_code == 200:
            image_url = ret['key']
            return image_url
        else:
            return ""

    def delete(self, key_str):
        """删除单个文件"""

        # 初始化BucketManager
        bucket = BucketManager(self.q)

        key = key_str
        # 删除bucket_name 中的文件 key
        ret, info = bucket.delete(self.bucket_name, key)
        # assert ret == {}

        if info.status_code == 200:
            return "删除成功"
        else:
            return "删除失败"

    def __str__(self):
        return "七牛云 上传和删除"


if __name__ == '__main__':
    qiniu_demo = QiNiu()
